package com.xiaoping.exacttimer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button mBtn1;
    private Button mBtn2;
    private int n = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mBtn1 = findViewById(R.id.btn1);
        mBtn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startMethod3();
            }
        });

        mBtn2 = findViewById(R.id.btn2);
        mBtn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCalHandler.removeCallbacks(mTicker);
            }
        });

    }

    private void startMethod3() {
        mCalHandler.post(mTicker);
    }

    private Handler mCalHandler = new Handler(Looper.getMainLooper());
    private final Runnable mTicker = new Runnable() {
        public void run() {
                long now = SystemClock.uptimeMillis();
                //long next = now + (1000 - now % 1000);
                long next = now + 1;
                mCalHandler.postAtTime(mTicker, next);//这个精确
                mBtn1.setText(next + "");
                Log.d("xxx","" + n++);//这个不精确
        }
    };

}